package com.daiziru.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.daiziru.common.Result;
import com.daiziru.entity.MUser;
import com.daiziru.service.MUserService;
import com.daiziru.util.ValidationUtil;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 作者：無言
 * 时间：2022/12/15 22:09
 * 描述：永无BUG
 */
@Controller
@RequestMapping("/authority")
public class AuthController extends BaseController{

    //谷歌工具类
    @Autowired
    Producer producer;

    @Autowired
    MUserService userService;

    //验证码生成
    @GetMapping("/captcha.jpg")
    public void kaptcha(HttpServletResponse resp) throws IOException {

        // 验证码
        String text = producer.createText();
        //验证码转图片
        BufferedImage image = producer.createImage(text);
        //验证码设置到session中
        req.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        //设置验证码不存在缓存里面
        resp.setHeader("Cache-Control", "no-store, no-cache");
        resp.setContentType("image/jpeg");
        ServletOutputStream outputStream = resp.getOutputStream();
        ImageIO.write(image, "jpg", outputStream);
    }


    @GetMapping("/login")
    public String login() {
        return "/auth/login";
    }

    @ResponseBody
    @PostMapping("/doLogin")
    public Result doLogin(String email, String password) {
        if(StrUtil.isEmpty(email) || StrUtil.isBlank(password)) {
            return Result.fail("邮箱或密码不能为空");
        }
        //创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken(email, SecureUtil.md5(password));
        try {
            //登录认证,跳转到Realm的认证
            SecurityUtils.getSubject().login(token);
        } catch (AuthenticationException e) {
            if (e instanceof UnknownAccountException) {
                return Result.fail("用户不存在");
            } else if (e instanceof LockedAccountException) {
                return Result.fail("用户被禁用");
            } else if (e instanceof IncorrectCredentialsException) {
                return Result.fail("密码错误");
            } else {
                return Result.fail("用户认证失败");
            }
        }
        //登录玩跳转到首页
        return Result.success().action("/");
    }

    @GetMapping("/register")
    public String register() {
        return "/auth/reg";
    }

    @ResponseBody
    @PostMapping("/doRegister")
    public Result doRegister(MUser user, String repass, String vercode) {

        //检验输入的注册信息
        ValidationUtil.ValidResult validResult = ValidationUtil.validateBean(user);
        if(validResult.hasErrors()) {
            return Result.fail(validResult.getErrors());
        }
        //校验密码
        if(!user.getPassword().equals(repass)) {
            return Result.fail("两次输入密码不相同");
        }

        //从session中获取验证码
        String captcha = (String) req.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println(captcha);
        //检验输入的验证码是否正确
        if(vercode == null || !vercode.equalsIgnoreCase(captcha)) {
            return Result.fail("验证码输入不正确");
        }
        //完成注册
        Result result = userService.register(user);
        //返回结果并跳转到登录页面（action是layui.js里面定义的）
        return result.action("/authority/login");
    }


    @RequestMapping ("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/index";
    }




}
